package com.example.yian.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yian.controller.SecurityRiskController;
import com.example.yian.entity.SecurityRisk;
import com.example.yian.entity.SecurityRiskReport;
import com.example.yian.entity.TextSearchRequest;
import com.example.yian.entity.TextSearchResponse;
import com.example.yian.mapper.TextSearchRequestMapper;
import com.example.yian.mapper.TextSearchResponseMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class TextSearchService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TextSearchRequestMapper textSearchRequestMapper;

    @Autowired
    private TextSearchResponseMapper textSearchResponseMapper;

    private static String strNewApiKey = "application-1dabbbdbf2be09c946ef401ca2412fdb";

    private static String strOldApiKey = "application-8900dd45b50a0e7d2b06bef61c526df0";

    private static final Logger log = LoggerFactory.getLogger(SecurityRiskController.class);

    private static Long curRequstId = 0L;

    public Long getCurRequstId() {
        return curRequstId;
    }

    public TextSearchRequest createRequest(String textMessage, Boolean reChat, Boolean stream, Long userId, Boolean isSave) {
        TextSearchRequest request = new TextSearchRequest();
        request.setTextMessage(textMessage);
        request.setReChat(reChat);
        request.setStream(stream);
        request.setUserId(userId);
        request.setCreatedAt(LocalDateTime.now());
        request.setIsSpecificationSearch(isSave);
        textSearchRequestMapper.insert(request);
        return request;
    }

    public TextSearchResponse createResponse(Long requestId, String chatId, String textId, Boolean operate,
                                             String content, String refText, Boolean isEnd, Boolean isSave) { // 修改这里
        TextSearchResponse response = new TextSearchResponse();
        log.info("createResponse | requestId : {}", requestId);
        response.setRequestId(requestId);

        curRequstId = requestId;
        log.info("createResponse | requestId : {}, after set: {}", requestId, response.getRequestId());
        response.setChatId(chatId);
        response.setTextId(textId);
        response.setOperate(operate);
        response.setContent(content);
        response.setRefText(refText);
        response.setIsEnd(isEnd);
        response.setCreatedAt(LocalDateTime.now());
        response.setUpdatedAt(LocalDateTime.now());

        // 检查数据库中是否存在相同的 text_id
        TextSearchResponse existingResponse = textSearchResponseMapper.selectByTextId(textId);

        if (existingResponse == null && isSave) {
            // 如果不存在相同的 text_id，则插入新记录
            textSearchResponseMapper.insert(response);
        } else {
            // 如果存在相同的 text_id 或者 isSave 为 false，返回已存在的记录或当前记录
            if (existingResponse != null) {
                response = existingResponse;
            }
        }
        return response;
    }

    public void InsertTextSearchResponse(Long requestId, String chatId, String textId, Boolean operate,
                                         String content, String refText, Boolean isEnd) { // 修改这里
        TextSearchResponse response = new TextSearchResponse();

        curRequstId = requestId;
        response.setRequestId(requestId);
        response.setChatId(chatId);
        response.setTextId(textId);
        response.setOperate(operate);
        response.setContent(content);
        response.setRefText(refText); // 修改这里
        response.setIsEnd(isEnd);
        response.setCreatedAt(LocalDateTime.now());
        response.setUpdatedAt(LocalDateTime.now());
        textSearchResponseMapper.insert(response);
    }

    public Optional<TextSearchRequest> findRequestById(Long requestId) {
        return Optional.ofNullable(textSearchRequestMapper.selectById(requestId));
    }

    public Optional<TextSearchResponse> findByTextId(String textId) {
        return Optional.ofNullable(textSearchResponseMapper.selectByTextId(textId));
    }


    public Map<String, Object> callThirdPartyApi(String chatId, String message, boolean reChat, boolean stream, boolean isSave) {
        String url = "http://120.26.5.41:8080/api/application/chat_message/" + chatId;
        HttpHeaders headers = new HttpHeaders();
        headers.set("accept", "application/json");
        if (isSave) {
            headers.set("Authorization", strOldApiKey);
        } else {
            headers.set("Authorization", strNewApiKey);
        }

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("message", message);
        requestBody.put("re_chat", reChat);
        requestBody.put("stream", stream);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
        // 检查状态码
        int statusCodeValue = response.getStatusCodeValue();
        if (statusCodeValue >= 200 && statusCodeValue < 300) {
            log.info("callThirdPartyApi |  请求成功");
        } else {
            // 请求失败
            log.error("callThirdPartyApi |  请求失败，状态码:" + statusCodeValue);
        }
        return response.getBody();
    }


    /**
     * 根据user_id分页获取隐患列表
     *
     * @param userId 用户ID
     * @param page   当前页码
     * @param size   每页数量
     * @return 分页后的隐患列表数据
     */
    public IPage<TextSearchRequest> getSearchRequstByUserIdWithPagination(Long userId, int page, int size, Boolean isSpecificationSearch, String startTime, String endTime) {
        int offset = (page - 1) * size;
        Page<TextSearchRequest> pageInfo = new Page<>(page, size);
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        List<TextSearchRequest> riskReports = textSearchRequestMapper.getSearchRequstByUserIdWithPagination(pageInfo, userId, startTime, endTime, size, offset, isSpecificationSearch);
        pageInfo.setRecords(riskReports);

        return pageInfo;
    }


    public List<Map<String, Object>> callLocalSearchApi(String chatId, String message, String tableName, boolean stream, boolean isSave) {
        String url = "http://120.26.5.41:8000/search";
        HttpHeaders headers = new HttpHeaders();
        headers.set("accept", "application/json");

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("text", message);
        requestBody.put("table_name", tableName);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        /*HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);*/
        ParameterizedTypeReference<List<Map<String, Object>>> responseType = new ParameterizedTypeReference<>() {
        };
        ResponseEntity<List<Map<String, Object>>> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);

        // 检查状态码
        int statusCodeValue = response.getStatusCodeValue();
        if (statusCodeValue >= 200 && statusCodeValue < 300) {
            log.info("callThirdPartyApi |  请求成功");
        } else {
            // 请求失败
            log.error("callThirdPartyApi |  请求失败，状态码:" + statusCodeValue);
        }

        return response.getBody();
        // 处理返回的列表数据
        /*List<Map<String, Object>> responseBody = response.getBody();
        if (responseBody != null) {
            // 进一步处理列表中的每个 Map 元素
            for (Map<String, Object> item : responseBody) {
                System.out.println(item);
                return item;
            }*/

    }

}